package main

import (
	"time"

	"gitee.com/fu-ce-wei/pi-mapper/pkg/logger"
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
)

// setupMiddlewares 设置中间件
func setupMiddlewares(router *gin.Engine, logger *logger.Logger) {
	// 日志中间件
	router.Use(createLoggingMiddleware(logger))

	// 跨域中间件
	router.Use(createCorsMiddleware())
}

// createLoggingMiddleware 创建日志中间件
func createLoggingMiddleware(logger *logger.Logger) gin.HandlerFunc {
	return func(c *gin.Context) {
		start := time.Now()
		path := c.Request.URL.Path

		c.Next()

		duration := time.Since(start)
		logger.Info("HTTP请求",
			zap.String("method", c.Request.Method),
			zap.String("path", path),
			zap.Int("status", c.Writer.Status()),
			zap.Duration("duration", duration),
			zap.String("client_ip", c.ClientIP()),
		)
	}
}

// createCorsMiddleware 创建跨域中间件
func createCorsMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		c.Header("Access-Control-Allow-Origin", "*")
		c.Header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
		c.Header("Access-Control-Allow-Headers", "Origin, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization")

		if c.Request.Method == "OPTIONS" {
			c.AbortWithStatus(204)
			return
		}

		c.Next()
	}
}
